package com.travel.recommend.service.impl;

import com.alibaba.fastjson.JSON;
import com.travel.common.vo.MemberRespVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.travel.common.utils.PageUtils;
import com.travel.common.utils.Query;

import com.travel.recommend.dao.InitialLikeTagDao;
import com.travel.recommend.entity.InitialLikeTagEntity;
import com.travel.recommend.service.InitialLikeTagService;

import static com.travel.common.constant.AuthServerConstant.LOGIN_USER;


@Service("initialLikeTagService")
public class InitialLikeTagServiceImpl extends ServiceImpl<InitialLikeTagDao, InitialLikeTagEntity> implements InitialLikeTagService {
    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<InitialLikeTagEntity> page = this.page(
                new Query<InitialLikeTagEntity>().getPage(params),
                new QueryWrapper<InitialLikeTagEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 获取指定用户的初始喜好标签
     * @param userId
     * @return
     */
    @Override
    public String getInitialLikeTag(Integer userId) {
        InitialLikeTagEntity entity = this.baseMapper.selectOne(new QueryWrapper<InitialLikeTagEntity>().eq("user_id", userId));
        if(entity == null){
            return null;
        }else{
            return entity.getInitialTag();
        }

    }

    /**
     * 保存初始喜好标签
     * @param initialLikeTag
     */
    @Override
    public void saveInitialLikeTag(String initialLikeTag) {
        //1. 从redis中取出用户信息
        String s = redisTemplate.opsForValue().get(LOGIN_USER);
        MemberRespVo loginUser = JSON.parseObject(s,MemberRespVo.class);
        Integer userId = loginUser.getMemberId().intValue();

        InitialLikeTagEntity entity = new InitialLikeTagEntity();
        entity.setUserId(userId);
        entity.setInitialTag(initialLikeTag);
        entity.setAddTime(new Date());
        entity.setUpdateTime(new Date());

        this.baseMapper.insert(entity);
    }

}